package com.jinzhi.jzweb.controller;


import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.Result;

/**
 * 
 * <pre>
 * 秘钥管理
 * </pre>
 * <small> 2023-12-26 11:35:35 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/zykResourcesSecretKey")
public class ZykResourcesSecretKeyController extends BaseController {

	private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

	@Autowired
	private ZykResourcesSecretKeyService zykResourcesSecretKeyService;

	@Autowired
	private ZykManagementSercetKeyService zykManagementSercetKeyService;

	@Autowired
	private ZykUserSercetKeyService zykUserSercetKeyService;

	@Autowired
	private ZykManagementResourcesService zykManagementResourcesService;

	@Autowired
	private JazSysProjectService jazSysProjectService;  //类型表

	@Autowired

	private ZykUserSercetKeyOnlyService zykUserSercetKeyOnlyService;

	
	@GetMapping()
	String ZykResourcesSecretKey(){
	    return "jzweb/zykResourcesSecretKey/zykResourcesSecretKey";
	}
	
	@ResponseBody
	@GetMapping("/list")
	public Result<Page<ZykResourcesSecretKeyDO>> list(ZykResourcesSecretKeyDO zykResourcesSecretKeyDTO){

		EntityWrapper selWrapper =new EntityWrapper();
		if (zykResourcesSecretKeyDTO.getSecretKey()!=null&&!zykResourcesSecretKeyDTO.getSecretKey().equals("")){
			selWrapper.eq("secret_key",zykResourcesSecretKeyDTO.getSecretKey()); //根据秘钥查询
		}
		if (zykResourcesSecretKeyDTO.getState()!=null){
			selWrapper.eq("state",zykResourcesSecretKeyDTO.getState()); //根据秘钥状态查询
		}
		if (zykResourcesSecretKeyDTO.getUseState()!=null){
			selWrapper.eq("use_state",zykResourcesSecretKeyDTO.getUseState()); //根据秘钥使用状态查询
		}
		// 查询列表数据
		Page<ZykResourcesSecretKeyDO> page = zykResourcesSecretKeyService.selectPage(getPage(ZykResourcesSecretKeyDO.class),selWrapper);
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
				ZykResourcesSecretKeyDO obj = (ZykResourcesSecretKeyDO) page.getRecords().get(i);
				EntityWrapper wrapper =new EntityWrapper();
				wrapper.eq("secret_key_id",obj.getId()); //秘钥id
				int rs = zykUserSercetKeyService.selectCount(wrapper);
				obj.setBdNumber(rs); //绑定人数
			list.add(obj);
		}
		page.setRecords(list);
        return Result.ok(page);
	}





	
	@GetMapping("/add")
	String add(Model model){
		//查询课程资源
		List<ZykManagementResourcesDO> zykManagementResourcesDOS = zykManagementResourcesService.selectList(null);
			// 根据projectId分成多个集合
			Map<String, List<ZykManagementResourcesDO>> groupedMap = new HashMap<>();
			for (ZykManagementResourcesDO resource : zykManagementResourcesDOS) {
				String projectId = resource.getProjectId();
				if (!groupedMap.containsKey(projectId)) {
					groupedMap.put(projectId, new ArrayList<>());
				}
				groupedMap.get(projectId).add(resource);
			}

			Map<String, List<ZykManagementResourcesDO>> modifiedMap = new HashMap<>();
			for (Map.Entry<String, List<ZykManagementResourcesDO>> entry : groupedMap.entrySet()) {
				String oldValue = entry.getKey();
				JazSysProjectDO jazSysProjectDO = jazSysProjectService.selectById(oldValue);
				String newValue = jazSysProjectDO.getName();
				List<ZykManagementResourcesDO> value = entry.getValue();
				modifiedMap.put(newValue, value);
			}
			model.addAttribute("coursesAll",modifiedMap);
			return "jzweb/zykResourcesSecretKey/add";
		}


	@GetMapping("/edit/{id}")
	String edit(@PathVariable("id") Long id,Model model){
		ZykResourcesSecretKeyDO zykResourcesSecretKey = zykResourcesSecretKeyService.selectById(id);
		model.addAttribute("zykResourcesSecretKey", zykResourcesSecretKey);
		//查询课程资源
		List<ZykManagementResourcesDO> zykManagementResourcesDOS = zykManagementResourcesService.selectList(null);
		//查询用户所拥有的课程资源
		EntityWrapper<ZykManagementSercetKeyDO> wrapper =new EntityWrapper<>();
		wrapper.eq("secret_key_id",id);
		List<ZykManagementSercetKeyDO> byUserAll = zykManagementSercetKeyService.selectList(wrapper);
		//表示没有任何资源，直接返回列表
		if (byUserAll.size()<1){
			// 根据projectId分成多个集合
			Map<String, List<ZykManagementResourcesDO>> groupedMap = new HashMap<>();
			for (ZykManagementResourcesDO resource : zykManagementResourcesDOS) {
				String projectId = resource.getProjectId();
				if (!groupedMap.containsKey(projectId)) {
					groupedMap.put(projectId, new ArrayList<>());
				}
				groupedMap.get(projectId).add(resource);
			}

			Map<String, List<ZykManagementResourcesDO>> modifiedMap = new HashMap<>();
			for (Map.Entry<String, List<ZykManagementResourcesDO>> entry : groupedMap.entrySet()) {
				String oldValue = entry.getKey();
				JazSysProjectDO jazSysProjectDO = jazSysProjectService.selectById(oldValue);
				String newValue = jazSysProjectDO.getName();
				List<ZykManagementResourcesDO> value = entry.getValue();
				modifiedMap.put(newValue, value);
			}
			model.addAttribute("coursesAll",modifiedMap);
			return "jzweb/zykResourcesSecretKey/edit";
		}
		//表示有资源需要显示它有哪些资源
		for (int i=0;i<byUserAll.size();i++){
			for (int j=0;j<zykManagementResourcesDOS.size();j++){
				//如果課程id相同
				if (zykManagementResourcesDOS.get(j).getId().equals(byUserAll.get(i).getManagementId())) {
					zykManagementResourcesDOS.get(j).setIsShow("1");
				}
			}
		}
		// 根据projectId分成多个集合
		Map<String, List<ZykManagementResourcesDO>> groupedMap = new HashMap<>();
		for (ZykManagementResourcesDO resource : zykManagementResourcesDOS) {
			String projectId = resource.getProjectId();
			if (!groupedMap.containsKey(projectId)) {
				groupedMap.put(projectId, new ArrayList<>());
			}
			groupedMap.get(projectId).add(resource);
		}

		Map<String, List<ZykManagementResourcesDO>> modifiedMap = new HashMap<>();
		for (Map.Entry<String, List<ZykManagementResourcesDO>> entry : groupedMap.entrySet()) {
			String oldValue = entry.getKey();
			JazSysProjectDO jazSysProjectDO = jazSysProjectService.selectById(oldValue);
			String newValue = jazSysProjectDO.getName();
			List<ZykManagementResourcesDO> value = entry.getValue();
			modifiedMap.put(newValue, value);
		}
		ZykResourcesSecretKeyDO zykResourcesSecretKeyDO = zykResourcesSecretKeyService.selectById(id);
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String formattedDate = dateFormat.format(zykResourcesSecretKeyDO.getEntDate());
		model.addAttribute("entDate",formattedDate);
		model.addAttribute("coursesAll",modifiedMap);
		return "jzweb/zykResourcesSecretKey/edit";
	}

	/**
	 *
	 * @param entDate 过期时间
	 * @param ids	课程id
	 * @param number	数量
	 * @param remark	备注
	 * @return
	 */
	@Log("添加秘钥管理")
	@ResponseBody
	@PostMapping("/save")
	@Transactional
	public Result<String> save(Date entDate,@RequestParam("ids[]") Long[] ids,Integer number,String remark,String schoolName){

		ZykResourcesSecretKeyDO zykResourcesSecretKeyDO =new ZykResourcesSecretKeyDO();
		zykResourcesSecretKeyDO.setSecretKey(generateKey(20));  //秘钥
		zykResourcesSecretKeyDO.setCreaterDate(new Date()); //创建时间
		zykResourcesSecretKeyDO.setNumber(number); //人数
		zykResourcesSecretKeyDO.setEntDate(entDate); //过期时间
		zykResourcesSecretKeyDO.setState(1); //秘钥状态，默认启用
		zykResourcesSecretKeyDO.setUseState(1); //0.已过期，1.使用中 默认使用中
		zykResourcesSecretKeyDO.setRemark(remark); //备注
		zykResourcesSecretKeyDO.setSchoolName(schoolName);//学校
		zykResourcesSecretKeyService.insert(zykResourcesSecretKeyDO);

		Long id = zykResourcesSecretKeyDO.getId();  //新增后的秘钥id
		List<ZykManagementSercetKeyDO> insertZykManagementSercetKeyDO =new ArrayList<>();
		for (int i=0;i<ids.length;i++){
			ZykManagementSercetKeyDO zykManagementSercetKeyDO = new ZykManagementSercetKeyDO();
			zykManagementSercetKeyDO.setSecretKeyId(id); //秘钥id
			zykManagementSercetKeyDO.setManagementId(ids[i]); //课程id
			insertZykManagementSercetKeyDO.add(zykManagementSercetKeyDO);
		}
		zykManagementSercetKeyService.insertBatch(insertZykManagementSercetKeyDO);  //批量增加课程权限与秘钥对应关系表
		return Result.ok();
	}


	public static String generateKey(int length) {
		StringBuilder sb = new StringBuilder(length);
		SecureRandom secureRandom = new SecureRandom();
		for (int i = 0; i < length; i++) {
			int index = secureRandom.nextInt(ALPHA_NUMERIC_STRING.length());
			sb.append(ALPHA_NUMERIC_STRING.charAt(index));
		}
		return sb.toString();
	}
	
	@Log("修改秘钥管理")
	@ResponseBody
	@RequestMapping("/update")
	public Result<String>  update( ZykResourcesSecretKeyDO zykResourcesSecretKey,@RequestParam("ids[]") Long[] ids){
		EntityWrapper wrapper =new EntityWrapper();
		wrapper.eq("secret_key_id",zykResourcesSecretKey.getId());
		List<ZykManagementSercetKeyDO> list = zykManagementSercetKeyService.selectList(wrapper);
		if (list.size()>0) {
			List<Long> idList = list.stream().map(ZykManagementSercetKeyDO::getId).collect(Collectors.toList()); // 将id收集到新的集合中
			zykManagementSercetKeyService.deleteBatchIds(idList);  //删除原有数据
		}
		List<ZykManagementSercetKeyDO> zykManagementSercetKeyDOS =new ArrayList<>();
		for (int i=0;i<ids.length;i++){
			ZykManagementSercetKeyDO zykManagementSercetKeyDO = new ZykManagementSercetKeyDO();
			zykManagementSercetKeyDO.setSecretKeyId(zykResourcesSecretKey.getId());
			zykManagementSercetKeyDO.setManagementId(ids[i]);
			zykManagementSercetKeyDOS.add(zykManagementSercetKeyDO);
		}
		zykManagementSercetKeyService.insertBatch(zykManagementSercetKeyDOS);
		boolean update = zykResourcesSecretKeyService.updateById(zykResourcesSecretKey);
		return update ? Result.ok() : Result.fail();
	}
	
	@Log("删除秘钥管理")
	@PostMapping( "/remove")
	@ResponseBody
	public Result<String>  remove(Long id){
		EntityWrapper wrapper =new EntityWrapper();
		wrapper.eq("secret_key_id",id);
		zykManagementSercetKeyService.delete(wrapper);//删除该秘钥关联的课程关系
		EntityWrapper wrapper2 =new EntityWrapper();
		wrapper2.eq("secret_key_id",id);
		zykUserSercetKeyService.delete(wrapper2); //删除该秘钥关联的用户关系
		zykUserSercetKeyOnlyService.delete(new EntityWrapper<ZykUserSercetKeyOnlyDO>().eq("secret_key_id",id)); //删除该秘钥关联的用户关系
		zykResourcesSecretKeyService.deleteById(id);
        return Result.ok();
	}
	
//	@Log("批量删除秘钥管理")
//	@PostMapping( "/batchRemove")
//	@ResponseBody
//	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
//		zykResourcesSecretKeyService.deleteBatchIds(Arrays.asList(ids));
//		return Result.ok();
//	}
	
}
